import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import webConfig from '@/global.config'

Vue.use(VueRouter)      //注册路由

// 路由表映射
const routes = [
    {
        path: "/login",
        name: "登录",
        hidden: true,
        component: () => import('../views/login/Login.vue')
    },
]


//创建路由实例并传递routs配置
const createRouter = () => new VueRouter({
    mode: 'history',    //历史模式
    routes, //路由规则，`routes: routes` 的缩写
})

const router = createRouter()

//重置路由
export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // reset router
}

//挂载路由守卫导航：to 将要访问的路径；from 代表从哪个路径跳转而来；next 是一个函数，表示放行
router.beforeEach((to, from, next) => {
    if (to.path === "/login") {
        console.log('跳转到登录页面')
        next();
    } else if (webConfig.whiteListApi.indexOf(to.path) === -1 && !store.state.accessToken) {
        Vue.prototype.$message.error("登录已过期!")
        next({path: '/login'});
    } else {
        next();
    }
});

// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return routerPush.call(this, location).catch(err => err)
}

export default router   //将路由缺省暴露出去，其他文件才可访问
